// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-11-22

#include "stdafx.h"
#include "tm_updatesvr.h"
#include "svr_asyncqueue.h"
#include "svr_server.h"
#include "db_utility.h"
#include "dbmsg_base.h"

namespace JoyServer
{

class CJoyAsyncUpdateServer : public CJoyAsyncObject
{
public:
    CJoyServer* m_server;

    virtual void OnExecute();
    CJoyAsyncUpdateServer(CJoyTmUpdateServer* tmUpdate)
    {
        m_server = tmUpdate->m_server;
    }
};

void CJoyAsyncUpdateServer::OnExecute()
{
    // open session from online server data source.
    CJoyDbSession sessOServ;
    if(!JoyOpenDbSession(m_server, sessOServ,
        m_server->m_dbSetOServ.GetSource(m_server->m_serverId)))
    {
        return;
    }

    CJoyDbCommand updateCmd;
    if(!JoyInvokeCommand(m_server, sessOServ, updateCmd,
        L"battle_update_server",
        m_server->m_serverId))
    {
        return;
    }

    while(HasMoreRow(updateCmd.MoveNext()))
    {
        m_server->m_dbMsgHandler->DbMsg_Rowset(updateCmd);
    }
}

// class CJoyTmUpdateServer

CJoyTmUpdateServer::CJoyTmUpdateServer()
{
    m_server        = NULL;
    m_asyncQueue    = NULL;
}

CJoyTmUpdateServer::~CJoyTmUpdateServer()
{
}

bool CJoyTmUpdateServer::Create(CJoyServer* pServer)
{
    m_server    = pServer;

    m_asyncQueue = new CJoyAsyncQueue();
    if(!m_asyncQueue->Create(pServer->m_asyncExec))
    {
        return false;
    }

    DWORD dwElapse = 15000;
    pServer->FindTiming("update_svr", dwElapse);

    if(!__super::Create(&pServer->m_timer, dwElapse))
    {
        return false;
    }
    return true;
}

void CJoyTmUpdateServer::Destroy()
{
    __super::Destroy();

    if(m_asyncQueue != NULL)
    {
        m_asyncQueue->Destroy();
        m_asyncQueue->Release();
        m_asyncQueue = NULL;
    }
}

void CJoyTmUpdateServer::OnExecute()
{
    if(m_asyncQueue->IsEmpty())
    {
        CJoyAsyncUpdateServer* asyncUpdate = new CJoyAsyncUpdateServer(this);
        m_asyncQueue->QueueObject(asyncUpdate);
    }
}


} // namespace JoyServer